package com.ruoyi.iot.influxdb.service;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.iot.config.Constants;
import com.ruoyi.iot.config.ResultModel;
import com.ruoyi.iot.config.ResultStatus;
import com.ruoyi.iot.influxdb.bean.DeviceData;
import com.ruoyi.iot.influxdb.bean.DeviceLogCount;
import com.ruoyi.iot.influxdb.config.dbquery.BuildResultService;
import com.ruoyi.iot.influxdb.config.dbquery.DataEntity;
import com.ruoyi.iot.influxdb.query.DeviceLogQuery;
import com.ruoyi.iot.influxdb.repository.metric.InfluxdbSqlBuilder;
import com.ruoyi.iot.influxdb.repository.metric.MetricsRepository;
import com.ruoyi.iot.util.DateUtils;
import com.ruoyi.iot.util.EmptyUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 远程设备控制
 * Created by Andy.Yang on 2020-03-15.
 */
@Component
@Order(value=1)
public class BlueToothDataCmdService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private InfluxDB influxDB;

    @Autowired
    private MetricsRepository<DeviceData> metricsRepository;

    @Autowired
    private BuildResultService<DeviceData> buildService;

    @Autowired
    private RedisCache redisCache;


    public ResultModel saveData(DeviceData metrics) throws InterruptedException {
        metricsRepository.save(metrics.getSerialNumber(), metrics,
                    true);
        redisCache.setCacheObject("device_detail_"+metrics.getDeviceId(), JSON.toJSONString(metrics));//设备详情放到缓存中
        // 添加告警数据
        responseAlarm(metrics);
        return ResultModel.ok();
    }
    public void responseAlarm(DeviceData metrics){
//        DeviceAlarm alarm = new DeviceAlarm();
//        alarm.setDeviceId(metrics.getDeviceId());
//        alarm.setAlarmTime(new Date());
//        alarm.setDeviceTypeId(47);
//        String tittle = "烟感报警";
//        String detail = "烟雾过浓，发生报警，请立即查看处理，防止火灾发生";
//        alarm.setOpen(1);
//        alarm.setTitle(tittle);
//        alarm.setDetail(detail);
//        deviceAlarmService.saveOne(alarm);
    }

    public ResultModel getDeviceDetailFromCache(String deviceId){
            Object o = redisCache.getCacheObject("device_detail_"+deviceId);
            return ResultModel.ok(o);
    }



    /**
     * 查询历史运行数据
     *
     * @param query
     * @param page
     * @return
     */
    public ResultModel findHistoryData(DeviceLogQuery query, Pageable page) {
        if (EmptyUtils.isEmpty(query.getStartDate()))
            query.setStartDate(DateUtils.getDateFromStr("1970-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        else
            query.setStartDate(DateUtils.getHourAfter(query.getStartDate(), -8));
        if (EmptyUtils.isEmpty(query.getEndDate()))
            query.setEndDate(DateUtils.getHourAfter(new Date(), -8));
        else
            query.setEndDate(DateUtils.getHourAfter(query.getEndDate(), -8));

        query.setCountColumn("serialNumber");
        query.setSelectColumns("*");
        query.setTableName(InfluxdbSqlBuilder.findMeasurementName(DeviceData.class));

        String countSql = InfluxdbSqlBuilder.buildCountSqlWithDetailByDeviceIdNOZONE(query);

        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper(); // thread-safe - can be reused
        Query dbQuery = new Query(countSql, Constants.INFLUXDB_DATABASE_PLAT);
        QueryResult queryResult = influxDB.query(dbQuery);

        List<DeviceLogCount> countsList = resultMapper.toPOJO(queryResult, DeviceLogCount.class);
        if (countsList.isEmpty())
            return ResultModel.error(ResultStatus.DATA_NOT_FOUND);// 没有数据

        int pageSize = EmptyUtils.isEmpty(page.getPageSize()) ? 1 : page.getPageSize();
        int pageNumber = EmptyUtils.isEmpty(page.getPageNumber()) ? 10 : page.getPageNumber();

        StringBuffer sb = new StringBuffer("select * FROM SmokeSafe WHERE 1 = 1 ");
        if (EmptyUtils.isNotEmpty(query.getDeviceId()))
            sb.append(" AND deviceId = '" + query.getDeviceId() + "' ");
//        if (EmptyUtils.isNotEmpty(query.getCollectNo()))
//            sb.append(" AND collectNo = '" + query.getCollectNo() + "' ");
        if (EmptyUtils.isNotEmpty(query.getStartDate()))
            sb.append(" AND time >= '" + DateUtils.getStrFromDate(query.getStartDate(), "yyyy-MM-dd HH:mm:ss") + "' ");

        if (EmptyUtils.isNotEmpty(query.getEndDate()))
            sb.append(" AND time <= '" + DateUtils.getStrFromDate(query.getEndDate(), "yyyy-MM-dd HH:mm:ss") + "' ");

        sb.append(" ORDER BY time DESC LIMIT " + pageSize + " OFFSET " + pageNumber * pageSize);

        dbQuery = new Query(sb.toString(), Constants.INFLUXDB_DATABASE_PLAT);
        queryResult = influxDB.query(dbQuery);
        List<DeviceData> metricsList = resultMapper.toPOJO(queryResult, DeviceData.class);

        DataEntity data = buildService.buildDataEntity(metricsList);
        data.getPage().setSize(page.getPageSize());
        data.getPage().setTotalElements(countsList.get(0).getCount());
        ResultModel result = new ResultModel(ResultStatus.SUCCESS, data);
        return result;
    }



}
